<?php

namespace App\Models\Cashier;

use Illuminate\Database\Eloquent\Model;
use Cache;

class Category extends Model
{
    protected $guarded = [];

    //一级分类下有很多二级分类
    public function children()
    {
        return $this->hasMany('App\Models\Cashier\Category', 'parent_id', 'id');
    }

    //一个分类有很多商品
    public function products()
    {
        return $this->hasMany('App\Models\Cashier\Product');
    }

    //清除缓存
    static function clear()
    {
        Cache::forget('cashier_categories');
    }


    /** 获取所有分类
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    static function get_categories()
    {
        $categories = Cache::rememberForever('cashier_categories', function () {
            return self::with([
                'children' => function ($query) {
                    $query->orderBy('sort_order');  //二级分类排序
                }
            ])->where('parent_id', 0)->orderBy('sort_order')->get(); //一级分类排序
        });
        return $categories;
    }


    /** 检查是否有二级分类
     * @param $id
     * @return bool
     */
    static function check_children($id)
    {
        $category = self::with('children')->find($id);
        if ($category->children->isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 筛选分类时,屏蔽掉没有商品的分类
     */
    static function filter_categories()
    {
        $categories = self::has('children.products')->with([
            'children' => function ($query) {
                $query->has('products');
            }
        ])->get();

        return $categories;
    }

    /**
     * 检查当前分类是否有商品
     */
    static function check_products($id)
    {
        $category = self::with('products')->find($id);
        if ($category->products->isEmpty()) {
            return true;
        }
        return false;
    }

}
